package ca.etsmtl.gti785;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import ca.etsmtl.gti785.classes.Application;
import ca.etsmtl.gti785.classes.Fichier;
import ca.etsmtl.gti785.classes.Server;
import ca.etsmtl.gti785.util.FileAdapter;
import ca.etsmtl.gti785.util.GPSTracker;
import ca.etsmtl.gti785.util.ServerAdapter;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

/**
 * Launcher activity of the client side application. It contains the main view of the application.
 * @author Etienne Faucher, Pierre-Mary Bien-Aimé
 */
public class MainActivity extends Activity 
{
	private Context _context = null;
	private Object _lock = new Object();
	private ApplicationObserver _observer;
	private final Handler _handler = new Handler();
	
	private final Runnable _updateResults = new Runnable() 
	{
        public void run() 
        {
        	UpdateUI();
        }
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		_context = this;
		_observer = new ApplicationObserver();
		Application.getInstanceOf().addObserver(_observer);
		Application.getInstanceOf().SetTracker(new GPSTracker(this));
		Application.getInstanceOf().LoadServers(this);
		
		final ListView serverView = (ListView) findViewById(R.id.server_list);
		final ServerAdapter adapter = new ServerAdapter(this, R.layout.server_layout, Application.getInstanceOf().getServers());
		serverView.setAdapter(adapter);
		serverView.setOnItemClickListener(new OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				final Server item = (Server) parent.getItemAtPosition(position);
				item.SetSelected(true);
				item.RemoveNotifications();
				
				for(int i = 0; i < parent.getCount(); i++)
				{
					if(i != position)
					{
						((Server) parent.getItemAtPosition(i)).SetSelected(false);
					}
				}
				
				if(item.GetSharedFolder() != null)
				{
					OnFileListClick(item.GetSharedFolder());
				}
				else
				{
					item.GetFiles();
					final ListView fileList = (ListView) findViewById(R.id.file_list);
					final FileAdapter adapter = new FileAdapter(_context, R.layout.file_list_item_layout, new ArrayList<Fichier>());
					fileList.setAdapter(adapter);
				}
			} 
		});
		
		UpdateUI();
	}
	
	public void OnFileListClick(Fichier item)
	{
		final ListView fileList = (ListView) findViewById(R.id.file_list);
		final FileAdapter adapter = new FileAdapter(_context, R.layout.file_list_item_layout, item.listFichiers);
		fileList.setAdapter(adapter);
		fileList.setOnItemClickListener(new OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				final Fichier item = (Fichier) parent.getItemAtPosition(position);
	        	Application.getInstanceOf().setSelectedFichier(item);
				if(item.isFolder)
				{
					new AlertDialog.Builder(_context)
					    .setTitle("Folder " + item.name)
					    .setMessage("Do you want to enter the folder or transfer it ?")
					    .setPositiveButton("Enter the folder", new DialogInterface.OnClickListener() 
					    {
					        public void onClick(DialogInterface dialog, int which) 
					        { 
					        	OnFileListClick(item);
					        }
					    })
					    .setNegativeButton("Transfer it", new DialogInterface.OnClickListener() 
					    {
					        public void onClick(DialogInterface dialog, int which) 
					        { 
					        	Intent intentChoisirServeur = new Intent(getApplicationContext(), ServerSelectionActivity.class);
								startActivity(intentChoisirServeur);
					        }
					    })
					    .setIcon(android.R.drawable.ic_dialog_alert).show();
				}
				else
				{
					Intent intentChoisirServeur = new Intent(getApplicationContext(), ServerSelectionActivity.class);
					startActivity(intentChoisirServeur);
				}
			}
		}); 
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.activity_menu, menu);
        return true;
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
	        case R.id.menu_addServer:
	        	try 
	        	{
	        	    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        	    intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes

	        	    startActivityForResult(intent, 0);
	        	} 
	        	catch (Exception e) 
	        	{
	        	    Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
	        	    Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
	        	    startActivity(marketIntent);
	        	}
	            return true;
	            
	        case R.id.menu_removeServer:
	        	if(Application.getInstanceOf().getSelectedServer() != null)
	        	{
	        		Application.getInstanceOf().RemoveServer(Application.getInstanceOf().getSelectedServer());
	        		UpdateUI();
	        	}
	        	else
	        	{
	        		Toast.makeText(getApplicationContext(), "No server selected!", Toast.LENGTH_LONG).show();
	        	}
	        	return true;
	            
	        case R.id.menu_getGlobalPosition:
	        	try
	        	{
	                if(Application.getInstanceOf().getGPSTracker().canGetLocation())
	                {
	                    double latitude = Application.getInstanceOf().getGPSTracker().getLatitude();
	                    double longitude = Application.getInstanceOf().getGPSTracker().getLongitude();
	                     
	                    Toast.makeText(getApplicationContext(), "Your Location is \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
	                }
	                else
	                {
	                	Application.getInstanceOf().getGPSTracker().showSettingsAlert();
	                }
	        	}
	        	catch(Exception e)
	        	{
	        		e.printStackTrace();
	        	}
	        	return true;
	           
	        default:
	            return super.onOptionsItemSelected(item);
        }
    } 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{           
	    super.onActivityResult(requestCode, resultCode, data);
	    if (requestCode == 0) 
	    {
	        if (resultCode == RESULT_OK) 
	        {
	            String contents = data.getStringExtra("SCAN_RESULT");
	            Server server = new Server(contents);
	            Application.getInstanceOf().AddServer(server);
	        }
	    }
	}
	
	public void UpdateUI()
	{
		synchronized(_lock)
		{
			final ListView view = (ListView) findViewById(R.id.server_list);
			final LinearLayout lview = (LinearLayout) findViewById(R.id.file_list_layout_background);
			final ListView fileList = (ListView) findViewById(R.id.file_list);
			view.invalidateViews();
			
			if(Application.getInstanceOf().getServers().isEmpty())
			{
				final FileAdapter adapter = new FileAdapter(_context, R.layout.file_list_item_layout, new ArrayList<Fichier>());
				fileList.setAdapter(adapter);
				lview.setBackgroundResource(R.drawable.server_add_centered);
			}
			else
			{
				lview.setBackgroundResource(0);
			}
		}
	}
	
	private class ApplicationObserver implements Observer
	{
		@Override
		public void update(Observable observable, Object data) 
		{
			_handler.post(_updateResults);
		}
	}
}
